/**
 * 
 */
package darwin8086.genetic;

/**
 * @author Dean
 *
 */

import java.util.*;
import java.io.*;

public class Gene implements Comparable<Gene>{
	private byte chromosome[];
	int id;
	float fitness;
	int timesRun;
	
	public Gene(int newID) {
		Random gen = new Random();
		chromosome = new byte[gen.nextInt(512)];
		gen.nextBytes(chromosome);
		id = newID;
		timesRun = 0;
	}
	
	public void WriteToFile(String filePath) {
		WriteToFile(filePath,id + ".com");
	}
	
	public void WriteToFile(String filePath, String botName){
		FileOutputStream out; 
		try {
			 out = new FileOutputStream(filePath + botName);
			 out.write(chromosome);
		}
        catch (Exception e)
        {
                System.err.println ("Error writing to file");
        }
	}
	
	public void UpdateFitness(float newFitness) {
		if(timesRun-1 != 0) {
			fitness = ((fitness/(timesRun-1)) + newFitness) / timesRun;
		}
		else {
			fitness = newFitness;
		}	
	}
	
	public float GetFitness() {
		return fitness;
	}	

	public int GetID() {
		return id;
	}
	
	public byte[] GetChromosome() {
		return chromosome;
	}
	
	public void SetChromosome(byte[] newChromo) {
		chromosome = newChromo;
		//if we change the choromosome, the fitness and times run need to be reset
		fitness = 0;
		timesRun = 0;
	}
	
	public void IncrementTimesRun() {
		timesRun++;
	}
	
	public String PrintChromosome() {
		String out = new String();
		for(int i=0;i<chromosome.length;i++) {
			out = Integer.toString( ( chromosome[i] & 0xff ) + 0x100, 16).substring( 1 ) + out;
		}
		return out;
	}
	
	public int compareTo(Gene anotherGene) { 
		if (this.fitness < anotherGene.GetFitness()) {
	    	return -1;
	    }
	    if (this.fitness > anotherGene.GetFitness()) {
	    	return 1;
	    }
	    return 0; //if both are equal
	}

}
